<!--外部指标管理-返回码管理-->
<template>
	<div>
		<div class="query-form">
			<yd-form ref="myForm" :options="formOptions" :model="queryParams">
				<template #form-btn>
					<div>
						<el-button class="yd-form-btn" type="primary" @click="handlerQuery()">查询</el-button>
					</div>
				</template>
			</yd-form>
		</div>
		<!-- 数据列表 -->
		<YdTable
			:formData="queryParams"
			:tableConfig="tableConfig"
			:tableData="tableData.data"
			@sizeChangeHandler="getList"
			@currentChangeHandler="getList"
			@sortChangeHandler="getList"
			@selectionChangeHandler="handlerSelectionChange"
		>
		</YdTable>
		<!-- 添加业务服务资源 -->
		<el-dialog :title="title" v-model="open" width="600px" append-to-body center>
			<el-form ref="codeForm" :model="form" :rules="rules" label-width="80px">
				<el-form-item label-width="100px" label="返回码名称" prop="name">
					<el-input v-model="form.name" maxlength="50" placeholder="请输入返回码名称" />
				</el-form-item>
				<el-form-item label-width="100px" label="类型名称" prop="typeId">
					<el-select v-model="form.typeId" clearable placeholder="请选择类型名称">
						<el-option v-for="item in typeNameOptions" :key="item.key" :label="item.value" :value="item.key"></el-option>
					</el-select>
				</el-form-item>
				<!-- <el-form-item label-width="100px" label="返回码数量" prop="codeCount">
					<el-input :disabled="true" v-model="form.codeCount" />
				</el-form-item> -->
				<el-form-item label-width="100px" label="返回码值" prop="value">
					<el-input v-model="form.value" placeholder="请输入返回码称值" />
				</el-form-item>
				<el-form-item label-width="100px" label="返回码说明" prop="explain">
					<el-input v-model="form.explain" placeholder="请输入返回码说明" />
				</el-form-item>
				<el-form-item label-width="100px" label="返回码状态" prop="status">
					<el-select v-model="form.status" clearable placeholder="请选择返回码状态">
						<el-option v-for="item in options.stateName" :key="item.key" :label="item.value" :value="item.key"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label-width="100px" label="状态级别" prop="level">
					<el-select v-model="form.level" clearable placeholder="请选择状态级别">
						<el-option v-for="item in options.levelName" :key="item.value" :label="item.label" :value="item.value"></el-option>
					</el-select>
				</el-form-item>
			</el-form>
			<template #footer>
				<el-button type="primary" @click="submitForm">确 定</el-button>
				<el-button @click="cancel">取 消</el-button>
			</template>
		</el-dialog>
		<!-- 添加业务服务资源 -->
		<el-dialog title="返回码详情配置" v-model="detailsOpen" width="900px" append-to-body center>
			<outside-code-management-details
				ref="detailsFormRef"
				:nameOptions="nameOptions"
				:name="name"
				:code="code"
				v-if="hackReset == true"
			></outside-code-management-details>
			<template #footer>
				<el-button @click="cancel">取 消</el-button>
			</template>
		</el-dialog>
		<!-- 上传upload -->
		<el-dialog title="返回码配置详细信息表模板导入" v-model="uploadOpen" width="600px" append-to-body center>
			<div style="text-align: center">
				<el-row>
					<el-button size="small" type="primary" @click="handlerDownloadTemplate">下载模板</el-button>
				</el-row>
				<div style="margin-top: 20px">
					<el-upload
						action="#"
						:limit="1"
						accept=".xlsx,.xls"
						:on-success="handlerSuccess"
						:on-change="fileChange"
						:on-remove="handlerRemove"
						:on-error="handlerError"
						:file-list="fileList"
						:auto-upload="false"
					>
						<el-button size="small" type="primary"> 上传</el-button>
					</el-upload>
				</div>
			</div>
			<template #footer>
				<el-button type="primary" @click="submitUploadForm">确 定</el-button>
				<el-button @click="cancel">取 消</el-button>
			</template>
		</el-dialog>
	</div>
</template>
<script setup name="OutsideCodeManagement" lang="ts">
import { getCodeList, save, edit, deleteData, getById, importTemplate, upload } from '@/api/admin/indicatorsManage/codeManagement';
import OutsideCodeManagementDetails from './codeManagementDetails.vue';
import { getCurrentInstance, reactive, ref, toRefs, watch } from 'vue';
import { downloadFromBlob } from '@/utils/common';
import { levelType } from '@/api/search/searchOptions';

const { proxy }: any = getCurrentInstance();

const open = ref(false);
const detailsOpen = ref(false);
const hackReset = ref(false);
// 选中数组
const ids = ref([]);
// 非单个禁用
const single = ref(true);
// 非多个禁用
const multiple = ref(true);
//弹出层标题
const title = ref('');
const formOptions = reactive<FormOptionType>([
	{
		type: 'input',
		label: '返回码名称',
		prop: 'name',
		placeholder: '请输入返回码名称',
		attrs: {
			clearable: true,
		},
	},
]);
// 表单校验
const rules = ref({
	name: [{ required: true, message: '返回码名称不能为空', trigger: 'blur' }],
	typeId: [{ required: true, message: '类型名称不能为空', trigger: 'blur' }],
	value: [{ required: true, message: '返回码值不能为空', trigger: 'blur' }],
	explain: [{ required: true, message: '返回码说明不能为空', trigger: 'blur' }],
	status: [{ required: true, message: '返回码状态不能为空', trigger: 'blur' }],
	level: [{ required: true, message: '状态级别不能为空', trigger: 'blur' }],
});
// 表单参数
const data = reactive<any>({
	form: {},
});
const { form }: any = toRefs(data);
// 返回码信息列表配置
let tableConfig = reactive({
	url: getCodeList,
	columns: [
		{
			label: '返回码名称',
			prop: 'name',
			// operation: [
			// 	{
			// 		text: undefined,
			// 		rowKey: 'name',
			// 		handler: (scope: any) => handleDetails(scope.row),
			// 	},
			// ],
		},
		{
			label: '类型名称',
			prop: 'typeId',
			formatter: (row: any, val: any) => {
				return typeNameOptions.value.filter((item: any) => item.key === val)[0].value;
			},
		},
		// {
		// 	label: '返回码数量',
		// 	prop: 'codeCount',
		// 	showOverFlowToolTip: true,
		// },
		{
			label: '返回码值',
			prop: 'value',
		},
		{
			label: '返回码说明',
			prop: 'explain',
		},
		{
			label: '返回码状态',
			prop: 'status',
			formatter: (row: any, val: any) => {
				let res = options.stateName.filter((item: any) => item.key === val);
				return res && res[0].value;
			},
		},
		{
			label: '状态级别',
			prop: 'level',
			formatter: (row: any, val: any) => {
				let res = options.levelName.filter((item: any) => item.value === Number(val));
				return res && res[0].label;
			},
		},
	],
	// 工具栏
	toolBar: [
		{ name: '新增', icon: 'yd-icon-plus', permi: ['outside:codeManagement:add'], handler: () => addHandle() },
		{ name: '修改', icon: 'yd-icon-edit', permi: ['outside:codeManagement:edit'], disable: 'single', handler: () => updateHandle() },
		{ name: '删除', icon: 'yd-icon-delete', permi: ['outside:codeManagement:delete'], disable: 'multiple', handler: () => deleteHandle() },
		{ name: '模板导入', icon: 'yd-icon-import', permi: ['outside:codeManagementDetails:import'], handler: () => uploadHandle() },
	],
	// 开启复选框
	enableSelection: true,
	// 开启分页
	pagination: {
		pageNum: 1,
		pageSize: 10,
		total: 0,
	},
	// 加载层
	loading: true,
});
// 未确认列表数据
let tableData = reactive({
	data: [],
	total: 0,
});
//返回码列表查询参数
let queryParams = reactive({
	pageNum: 1,
	pageSize: 10,
});
const typeNameOptions = ref([
	{
		key: 1,
		value: 'WEB返回码',
	},
	{
		key: 2,
		value: '中间件返回码',
	},
	{
		key: 3,
		value: '数据库返回码',
	},
	{
		key: 4,
		value: '自定义返回码',
	},
]);
let options = reactive({
	stateName: [
		{
			key: 0,
			value: '异常',
		},
		{
			key: 1,
			value: '正常',
		},
	],
	levelName: [] as any,
});
const nameOptions = ref([]);
const name = ref('');
let code = ref('');

const uploadOpen = ref(false);
const fileList = ref([] as any);

watch(detailsOpen, (newVal, oldVal) => {
	// 返回码详情页，当新增返回码后点击关闭该窗口（detailsOpen由true变成false）时刷新页面获取最新列表数据
	if (newVal === false && oldVal === true) {
		getList();
	}
});

function getLevelNameList() {
	levelType().then((response: ApiResponse | any) => {
		options.levelName = response.data.map((item: any) => ({ ...item, value: Number(item.value) }));
	});
}
/** 模板导入 */
function uploadHandle() {
	fileList.value = [];
	uploadOpen.value = true;
}
function handlerDownloadTemplate() {
	importTemplate().then((response: ApiResponse | any) => {
		downloadFromBlob(response, '返回码配置详细信息表模板');
	});
}
function fileChange(file: any) {
	fileList.value[0] = file.raw;
}
function handlerRemove() {
	fileList.value = [];
}
function handlerSuccess() {
	proxy.$modal.msgSuccess('上传成功，点击确认导入!');
}
function handlerError() {
	proxy.$modal.msgError('上传失败');
}
/** 导入提交按钮 */
function submitUploadForm() {
	if (fileList.value[0]) {
		let form = new FormData();
		const isXLS =
			fileList.value[0].type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
			fileList.value[0].type === 'application/vnd.ms-sheet' ||
			fileList.value[0].type === 'application/vnd.ms-excel';
		if (!isXLS) {
			proxy.$modal.msgError('请上传Excel文件');
			return;
		}
		const isLt5M = fileList.value[0].size / 1024 / 1024 < 5;
		if (!isLt5M) {
			proxy.$modal.msgError('文件大小不能超过5M');
		} else {
			form.append('file', fileList.value[0]);
			upload(form).then((rs: ApiResponse | any) => {
				if (rs.code === 0) {
					proxy.$modal.msgSuccess(rs.data);
					handlerQuery();
					uploadOpen.value = false;
				} else {
					proxy.$modal.msgError(rs.msg);
				}
			});
		}
	} else {
		proxy.$modal.msgError('请先上传文件');
	}
}
/** 查询返回码列表 */
function getList() {
	tableConfig.loading = true;
	getCodeList(queryParams)
		.then((response: ApiResponse | any) => {
			tableData.data = response.data.records;
			nameOptions.value = tableData.data;
			tableConfig.pagination.total = response.data.total;
			tableConfig.loading = false;
		})
		.catch((e: any) => {
			tableConfig.loading = false;
		});
}
/** 返回码搜索按钮操作 */
function handlerQuery() {
	getList();
}
/** 新增按钮操作 */
function addHandle() {
	reset();
	title.value = '新增返回码';
	open.value = true;
}
/** 修改按钮操作 */
function updateHandle() {
	reset();
	title.value = '编辑返回码';
	const id = ids.value;
	getById(id).then((response: ApiResponse | any) => {
		form.value = response.data.records[0];
		open.value = true;
	});
}
/** 删除按钮操作 */
function deleteHandle() {
	proxy.$modal
		.confirm('确定删除?', '警告', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			cancelButtonClass: 'confirm-rigth-cancel-button',
			type: 'warning',
		})
		.then(() => {
			deleteData(ids.value).then((res: ApiResponse | any) => {
				if (res.code === 0) {
					// 删除后的总条数
					let totalCount = tableConfig.pagination.total - ids.value.length;
					// 计算删除后的总页数
					let totalPage = Math.ceil(totalCount / queryParams.pageSize);
					// 如果删除后的总页数小于1, 置为1
					totalPage = totalPage < 1 ? 1 : totalPage;
					// 判断删除前的页数是否大于删除后的总页数, 计算当前页应该是多少赋值给查询表单
					queryParams.pageNum = queryParams.pageNum > totalPage ? totalPage : queryParams.pageNum;
					proxy.$modal.msgSuccess('删除成功');
					handlerQuery();
				} else {
					proxy.$modal.msgWarning(res.msg);
				}
			});
		})
		.catch(() => {});
}
/** 确认提交按钮 */
function submitForm() {
	proxy.$refs['codeForm'].validate((valid: boolean | any) => {
		if (valid) {
			let api = form.value.id ? edit : save;
			api(form.value).then((response: ApiResponse | any) => {
				if (response.code === 0) {
					if (form.value.id !== undefined) {
						proxy.$modal.msgSuccess('修改成功');
					} else {
						proxy.$modal.msgSuccess('新增成功');
					}
					open.value = false;
					getList();
				} else {
					proxy.$modal.msgError(response.msg);
				}
			});
		}
	});
}
// 取消按钮
function cancel() {
	open.value = false;
	detailsOpen.value = false;
	uploadOpen.value = false;
}
function reset() {
	form.value = {};
	// proxy.resetForm('codeForm');
	form.value.codeCount = 0;
}
// 多选框选中数据
function handlerSelectionChange(selection: any) {
	ids.value = selection.map((item: any) => item.id);
	single.value = selection.length !== 1;
	multiple.value = !selection.length;
}
const detailsFormRef = ref();
function handleDetails(row: any) {
	detailsOpen.value = true;
	hackReset.value = true;
	name.value = row.value;
	code.value = row.value;
	// let option = [];
	// getIdAndName().then((re) => {
	// 	re.result.forEach((item) => {
	// 		option.push({ label: item.name, value: item.name });
	// 	});
	// 	nameOptions.value = option;
	// 	hackReset.value = false;
	// 	proxy.$nextTick(() => {

	// 	});
	// 	detailsOpen.value = true;
	// });
}
getList();
getLevelNameList();
</script>
